package com.lfg.leetcode.leetcode0;

/**
 *
 */
public class KMP {

    public static int[] getNext(String content) {
        int length = content.length();
        int[] next = new int[length];
        next[0] = -1;
        int k = -1;
        for (int j = 0; j < length - 1; ) {
            if (k == -1 || content.charAt(k) == content.charAt(j)) {
                next[++j] = ++k;
            } else {
                k = next[k];
            }
        }
        return next;
    }

    public static void main(String[] args) {

        int[] ret = getNext("aaabbbcccaa");
        for (int i : ret) {
            System.out.print(i + ", ");
        }

        System.out.println("");
        int[] ret2 = getNext2("aaabbbcccaa");
        for (int i : ret2) {
            System.out.print(i + ", ");
        }

        System.out.println("");
    }


    public static int[] getNext2(String ps) {
        char[] p = ps.toCharArray();
        int[] next = new int[p.length];
        next[0] = -1;
        int j = 0;
        int k = -1;
        while (j < p.length - 1) {
            if (k == -1 || p[j] == p[k]) {
                if (p[++j] == p[++k]) { // 当两个字符相等时要跳过
                    next[j] = next[k];
                } else {
                    next[j] = k;
                }
            } else {
                k = next[k];
            }
        }
        return next;
    }
}
